package com.xqboss.common.utils;

import cn.hutool.core.collection.CollUtil;
import com.xqboss.common.utils.spring.SpringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

/**
 * TODO: 异步处理工具类
 *
 * @author lujiahong
 * @date 2021/8/19 11:17
 */
public class AsyncHandlerUtil<T> {
    /*获取自定义线程池*/
    private static final ThreadPoolTaskExecutor threadPoolTaskExecutor = SpringUtils.getBean(ThreadPoolTaskExecutor.class);

    /*无返回值*/
    public static CompletableFuture<Void> run(Runnable runnable){
        return CompletableFuture.runAsync(runnable, threadPoolTaskExecutor);
    }

    public static List<CompletableFuture<Void>> runAll(Runnable... runnables){
        return runAll(CollUtil.toList(runnables));
    }

    public static List<CompletableFuture<Void>> runAll(List<Runnable> runnables){
        List<CompletableFuture<Void>> futures = CollUtil.newArrayList();
        runnables.forEach(runnable -> futures.add(run(runnable)));
        return futures;
    }

    public static void runAllJoin(List<Runnable> runnables){
        List<CompletableFuture<Void>> futures = runAll(runnables);
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
    }

    /*有返回值*/
    public static <U> CompletableFuture<U> supplier(Supplier<U> supplier){
        return CompletableFuture.supplyAsync(supplier, threadPoolTaskExecutor);
    }
}
